package com.seo.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.seo.pojo.ReturnBody;
import com.seo.resolver.DefiniteException;
import com.seo.service.proxy.sdk.ProxyUserService;
import com.seo.utils.ClientConst;

import lombok.extern.slf4j.Slf4j;

/**
 * WapLoginSecurityInterceptor
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
public class ProxyUserLoginSecurityInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private ProxyUserService proxyUserService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		log.info("进入代理登录拦截器...");

		ReturnBody rb = ReturnBody.init();

		Object obj = request.getSession().getAttribute(ClientConst.SESSION_PROXY_USER);

		String requestType = request.getHeader("X-Requested-With");
		if (obj == null) {
			// 是否是AJAX登陆

			if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
				response.sendRedirect("/proxy/login");
			} else {

				rb.error("loginOut", "用户未登录");
				rb.getResult().setUrl("/proxy/login");
				returnJSON(response, rb);
			}
			return false;
		} else {
			Integer id = (Integer) ((Map<String, Object>) obj).get("id");
			Map<String, Object> proxyUser = proxyUserService.getProxyUserById(id);
			String state = (String) proxyUser.get("state");
			if (!"01".equals(state)) {
				if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
					throw new DefiniteException("用户被禁用");
				} else {
					rb.error("用户被禁用");
					returnJSON(response, rb);
				}
				return false;
			}
		}

		return true;
	}

	public void returnJSON(HttpServletResponse response, ReturnBody rb) throws Exception {
		ObjectMapper om = new ObjectMapper();
		response.getWriter().print(om.writeValueAsString(rb));
	}

}
